public class HeapSort {
    public static void heapSort(int[] arr) {
        createBigHeap(arr);
        int end = arr.length - 1;
        while (end > 0) {
            swap(arr, 0, end);
            shiftDown(arr, 0, end);
            end--;
        }
    }

    private static void createBigHeap(int[] arr) {
        int parent = (arr.length-2) / 2;
        while (parent >= 0) {
            int child = 2 * parent + 1;
            if (child + 1 < arr.length && arr[child] < arr[child + 1]) {
                child++;
            }
            if (arr[parent] < arr[child]) {
                swap(arr, parent, child);
                shiftDown(arr, child, arr.length);
            }
            parent--;
        }
    }

    private static void shiftDown(int[] arr, int parent, int length) {
        int child = 2 * parent + 1;
        while (child < length) {
            if (child + 1 < length && arr[child] < arr[child + 1]) {
                child++;
            }
            if (arr[parent] < arr[child]) {
                swap(arr, parent, child);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = { 12, 11, 13, 5, 6, 7 };
        heapSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}